package com.ukefu.webim.web.handler.admin.callcenter;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.ukefu.core.UKDataContext;
import com.ukefu.util.Menu;
import com.ukefu.util.freeswitch.model.CallCenterAgent;
import com.ukefu.webim.service.cache.CacheHelper;
import com.ukefu.webim.service.impl.CallOutQuene;
import com.ukefu.webim.service.repository.ExtentionRepository;
import com.ukefu.webim.service.repository.MediaRepository;
import com.ukefu.webim.service.repository.NumberPoolRepository;
import com.ukefu.webim.service.repository.PbxHostRepository;
import com.ukefu.webim.service.repository.QueSurveyProcessRepository;
import com.ukefu.webim.service.repository.SalesPatterRepository;
import com.ukefu.webim.service.repository.ServiceAiRepository;
import com.ukefu.webim.service.repository.SipTrunkRepository;
import com.ukefu.webim.service.repository.TenantRepository;
import com.ukefu.webim.service.repository.UserRepository;
import com.ukefu.webim.util.RobotTools;
import com.ukefu.webim.web.handler.Handler;
import com.ukefu.webim.web.model.Extention;
import com.ukefu.webim.web.model.PbxHost;
import com.ukefu.webim.web.model.User;

@Controller
@RequestMapping("/admin/callcenter")
public class CallCenterExtentionController extends Handler{
	
	@Autowired
	private PbxHostRepository pbxHostRes ;
	
	@Autowired
	private UserRepository userRes ;
	
	@Autowired
	private ExtentionRepository extentionRes;
	
	@Autowired
	private SipTrunkRepository sipTrunkRes ;
	
	@Autowired
	private MediaRepository mediaRes ;
	
	@Autowired
	private ServiceAiRepository serviceAiRes ;
	
	@Autowired
	private SalesPatterRepository salesPatterRes ;
	
	@Autowired
	private QueSurveyProcessRepository queSurveyProcessRes ;
	
	@Autowired
	private NumberPoolRepository numberPoolRepository;

	@Autowired
	private TenantRepository tenantRepository;

	@RequestMapping(value = "/extention")
    @Menu(type = "callcenter" , subtype = "callcenterresource" , access = false )
    public ModelAndView extention(ModelMap map , HttpServletRequest request , @Valid final String hostid, @Valid boolean ismy, @Valid final Extention extention, @Valid final Boolean isassigned, @Valid final String orgi1) {
		PbxHost pbxHost = pbxHostRes.findById(hostid) ;
		//map.addAttribute("pbxHostList" , pbxHostList);
		if(pbxHost != null){
			map.addAttribute("pbxHost" , pbxHost);

			if(super.isEnabletneantAndSuperUser(request)){
				Page<Extention> extentionPageList = extentionRes.findAll(new Specification<Extention>() {
					@Override
					public Predicate toPredicate(Root<Extention> root,
												 CriteriaQuery<?> query, CriteriaBuilder cb) {
						List<Predicate> list = new ArrayList<Predicate>();
						list.add(cb.equal(root.get("hostid").as(String.class), hostid));
						if(StringUtils.isNotBlank(orgi1)){
							list.add(cb.equal(root.get("orgi").as(String.class),orgi1));
						}
						if(isassigned != null){
							list.add(cb.equal(root.get("assigned").as(Boolean.class),isassigned));
						}
						Predicate[] p = new Predicate[list.size()];
						return cb.and(list.toArray(p));
					}
				}, new PageRequest(super.getP(request), super.getPs(request) , Sort.Direction.ASC, "extention","createtime"));
				//启用多租户和超级管理员 显示全部
				map.addAttribute("extentionList" , extentionPageList.getContent());
				map.addAttribute("extentionPageList" , extentionPageList);
				map.addAttribute("extention" , extention);
				map.addAttribute("orgi1" , orgi1);
				map.addAttribute("isassigned" , isassigned);

				map.addAttribute("tenantList",tenantRepository.findByDatastatus(false));
			}else{
				map.addAttribute("extentionList" , extentionRes.findByHostidAndOrgi(pbxHost.getId() , super.getOrgi(request)));
			}
			
			map.addAttribute("sipTrunkListList" , sipTrunkRes.findByHostidAndOrgi(hostid, super.getOrgi(request)));
		}
		if (ismy) {
			map.addAttribute("ismy",true);
		}
		map.put("p", super.getP(request)+1);
		return request(super.createRequestPageTempletResponse("/admin/callcenter/extention/index"));
    }
	
	@RequestMapping(value = "/extention/add")
    @Menu(type = "callcenter" , subtype = "extention" , access = false )
    public ModelAndView extentionadd(ModelMap map , HttpServletRequest request , @Valid String hostid) {
		if(super.isEnabletneant()){
			map.addAttribute("pbxHost" , pbxHostRes.findById(hostid));
		}else{
			map.addAttribute("pbxHost" , pbxHostRes.findByIdAndOrgi(hostid, super.getOrgi(request)));
		}
		map.addAttribute("sipTrunkListList" , sipTrunkRes.findByHostidAndOrgi(hostid, super.getOrgi(request)));

		map.addAttribute("numberPoolList",numberPoolRepository.findByHostid(hostid));

		if(super.isEnabletneantAndSuperUser(request)) {
			//多租户下 可以绑定租户
			map.addAttribute("tenantList", tenantRepository.findByDatastatus(false));
		}
		if(super.isEnabletneantAndSuperUser(request)){
			//启用多租户和超级管理员 显示全部
			map.addAttribute("mediaList" , mediaRes.findByHostid(hostid));
		}else{
			map.addAttribute("mediaList" , mediaRes.findByHostidAndOrgi(hostid, super.getOrgi(request)));
		}
    	return request(super.createRequestPageTempletResponse("/admin/callcenter/extention/add"));
    }
	
	@RequestMapping(value = "/extention/save")
    @Menu(type = "callcenter" , subtype = "extention" , access = false )
    public ModelAndView extentionsave(ModelMap map , HttpServletRequest request , @Valid Extention extention,@Valid String[] numberPool) {
		if(!StringUtils.isBlank(extention.getExtention()) && !StringUtils.isBlank(extention.getPassword())){
			String[] extstr = extention.getExtention().split("[,， ]") ;
			int extnum = 0 ;
			PbxHost pbxHost = pbxHostRes.findById(extention.getHostid());
			String orgi = pbxHost!=null?pbxHost.getOrgi():super.getOrgi(request);

			for(String ext : extstr){
				if(ext.matches("[\\d]{3,11}")){	//分机号码最少3位数字
					createNewExtention(ext, super.getUser(request), extention.getHostid(), extention.getPassword(), orgi , extention,numberPool) ;
				}else{
					String[] ph = ext.split("[~-]") ;
					if(ph.length == 2 && ph[0].matches("[\\d]{3,11}") && ph[1].matches("[\\d]{3,11}") && ph[0].length() == ph[1].length()){
						BigInteger start = new BigInteger(ph[0].toString());
						BigInteger end = new BigInteger(ph[1].toString());

						for(BigInteger i= start ; (i.compareTo(end) == -1 || i.compareTo(end) == 0) && extnum < 100 ; i = i.add(BigInteger.valueOf(1))){	//最大一次批量生产的 分机号不超过100个
							createNewExtention(String.valueOf(i), super.getUser(request), extention.getHostid(), extention.getPassword(), orgi , extention,numberPool) ;
							extnum++;
						}
						
					}
				}
			}
		}
		return request(super.createRequestPageTempletResponse("redirect:/admin/callcenter/extention.html?hostid="+extention.getHostid()));
    }
	
	private Extention createNewExtention(String num , User user , String hostid , String password , String orgi , Extention src,String[] numberPool){
		Extention extno = new Extention();
		extno.setExtention(num);
		extno.setOrgi(orgi);
		extno.setCreater(user.getId());
		extno.setHostid(hostid);
		extno.setPassword(password);
		
		extno.setPlaynum(src.isPlaynum());
		extno.setCallout(src.isCallout());
		extno.setRecord(src.isRecord());
		extno.setExtype(src.getExtype());
		extno.setMediapath(src.getMediapath());
		
		extno.setSiptrunk(src.getSiptrunk());
		extno.setEnablewebrtc(src.isEnablewebrtc());
		extno.setAutoanswer(src.getAutoanswer());
		
		extno.setOutnum(src.getOutnum());
		//int count = extentionRes.countByExtentionAndHostidAndOrgi(extno.getExtention() , hostid, orgi) ;
		//NOTE 同一个语音服务器下的分机唯一性 不管orgi是否一样
		int count = extentionRes.countByExtentionAndHostid(extno.getExtention() , hostid) ;
		if(count == 0){	
			extentionRes.save(extno) ;
		}
		return extno ;
	}
	
	@RequestMapping(value = "/extention/edit")
    @Menu(type = "callcenter" , subtype = "extention" , access = false )
    public ModelAndView extentionedit(ModelMap map , HttpServletRequest request , @Valid String id , @Valid String hostid, @Valid boolean ismy) {
		//多租户下超级管理员可以编辑其他租户
		if(super.isEnabletneantAndSuperUser(request)){
			map.addAttribute("extention" , extentionRes.findById(id));
		}else{
			map.addAttribute("extention" , extentionRes.findByIdAndOrgi(id, super.getOrgi(request)));
		}

		map.put("pbxHost", pbxHostRes.findByIdAndOrgi(hostid, super.getOrgi(request))) ;
		map.put("mediaList" , mediaRes.findByHostidAndOrgi(hostid, super.getOrgi(request)));
		map.addAttribute("sipTrunkListList" , sipTrunkRes.findByHostidAndOrgi(hostid, super.getOrgi(request)));

		map.addAttribute("numberPoolList",numberPoolRepository.findByHostid(hostid));

		map.addAttribute("numberPoolExtentionRelaList",numberPoolRepository.findByExtentionid(id));

		if (ismy) {
			map.addAttribute("ismy", ismy);
		}
		map.put("p", request.getParameter("p"));
    	return request(super.createRequestPageTempletResponse("/admin/callcenter/extention/edit"));
    }
	
	@RequestMapping(value = "/extention/update")
    @Menu(type = "callcenter" , subtype = "extention" , access = false )
    public ModelAndView extentionupdate(ModelMap map , HttpServletRequest request , @Valid Extention extention,@Valid String[] numberPool, @Valid boolean ismy) {
		if(!StringUtils.isBlank(extention.getId())){
			Extention ext = null;
			//多租户下超级管理员可以编辑其他租户
			if(super.isEnabletneantAndSuperUser(request)){
				ext = extentionRes.findById(extention.getId()) ;
			}else{
				ext = extentionRes.findByIdAndOrgi(extention.getId(), super.getOrgi(request)) ;
			}

			if(ext!=null){
//				ext.setExtention(extention.getExtention());//分机号不能修改
				if(!StringUtils.isBlank(extention.getPassword())){
					ext.setPassword(extention.getPassword());
				}
				ext.setPlaynum(extention.isPlaynum());
				ext.setCallout(extention.isCallout());
				ext.setRecord(extention.isRecord());
				ext.setExtype(extention.getExtype());
				ext.setSubtype(extention.getSubtype());
				ext.setDescription(extention.getDescription());
				
				ext.setAfterprocess(extention.isAfterprocess());
				
				ext.setMediapath(extention.getMediapath());
				
				ext.setSiptrunk(extention.getSiptrunk());
				ext.setEnablewebrtc(extention.isEnablewebrtc());
				
				ext.setAutoanswer(extention.getAutoanswer());
				
				ext.setOutnum(extention.getOutnum());
				
				ext.setUpdatetime(new Date());
				extentionRes.save(ext) ;

				List<CallCenterAgent> callOutAgentList = CallOutQuene.extention(ext.getExtention()) ;
				for(CallCenterAgent callOutAgent : callOutAgentList) {
					callOutAgent.setSiptrunk(ext.getSiptrunk());
					CacheHelper.getCallCenterAgentCacheBean().put(callOutAgent.getUserid(), callOutAgent, callOutAgent.getOrgi());
				}
				if(RobotTools.extention(ext.getExtention())) {
					RobotTools.putExtention(ext.getExtention(), ext);
				}
			}
		}
		return request(super.createRequestPageTempletResponse("redirect:/admin/callcenter/extention.html?hostid="+extention.getHostid()+(ismy?"&ismy=true":"")+"&p="+request.getParameter("p")));
    }
	
	@RequestMapping(value = "/extention/batedit")
    @Menu(type = "callcenter" , subtype = "extention" , access = false )
    public ModelAndView batedit(ModelMap map , HttpServletRequest request , @Valid String[] ids , @Valid String hostid, @Valid boolean ismy) {
		map.put("extentionList", extentionRes.findAll(Arrays.asList(ids)));
		map.put("pbxHost", pbxHostRes.findByIdAndOrgi(hostid, super.getOrgi(request))) ;
		map.put("mediaList" , mediaRes.findByHostidAndOrgi(hostid, super.getOrgi(request)));
		map.addAttribute("sipTrunkListList" , sipTrunkRes.findByHostidAndOrgi(hostid, super.getOrgi(request)));
		map.addAttribute("numberPoolList",numberPoolRepository.findByHostid(hostid));
		if (ismy) {
			map.addAttribute("ismy", ismy);
		}
    	return request(super.createRequestPageTempletResponse("/admin/callcenter/extention/batedit"));
    }
	
	@RequestMapping(value = "/extention/batupdate")
    @Menu(type = "callcenter" , subtype = "extention" , access = false )
    public ModelAndView batupdate(ModelMap map , HttpServletRequest request , @Valid String[] ids,@Valid Extention extention,@Valid String[] numberPool, @Valid boolean ismy) {
		if(ids!=null && ids.length > 0){
			List<Extention> extentions = extentionRes.findAll(Arrays.asList(ids)) ;
			for(Extention ext : extentions){
				if(!StringUtils.isBlank(extention.getPassword())){
					ext.setPassword(extention.getPassword());
				}
				ext.setPlaynum(extention.isPlaynum());
				ext.setCallout(extention.isCallout());
				ext.setRecord(extention.isRecord());
				if(!StringUtils.isBlank(extention.getExtype())) {
					ext.setExtype(extention.getExtype());
				}
				if(!StringUtils.isBlank(extention.getSubtype())) {
					ext.setSubtype(extention.getSubtype());
				}
				if(!StringUtils.isBlank(extention.getDescription())) {
					ext.setDescription(extention.getDescription());
				}
				
				if(!StringUtils.isBlank(extention.getMediapath())) {
					ext.setMediapath(extention.getMediapath());
				}
				
				if(!StringUtils.isBlank(extention.getSiptrunk())) {
					ext.setSiptrunk(extention.getSiptrunk());
				}
				
				ext.setEnablewebrtc(extention.isEnablewebrtc());
				
				if(!StringUtils.isBlank(extention.getAutoanswer())) {
					ext.setAutoanswer(extention.getAutoanswer());
				}
				
				if(!StringUtils.isBlank(extention.getOutnum())) {
					ext.setOutnum(extention.getOutnum());
				}
				
				ext.setAfterprocess(extention.isAfterprocess());
				
				extentionRes.save(ext) ;
				if(RobotTools.extention(ext.getExtention())) {
					RobotTools.putExtention(ext.getExtention(), ext);
				}
				List<CallCenterAgent> callOutAgentList = CallOutQuene.extention(ext.getExtention()) ;
				for(CallCenterAgent callOutAgent : callOutAgentList) {
					callOutAgent.setSiptrunk(ext.getSiptrunk());
					CacheHelper.getCallCenterAgentCacheBean().put(callOutAgent.getUserid(), callOutAgent, callOutAgent.getOrgi());
				}
			}
		}
		return request(super.createRequestPageTempletResponse("redirect:/admin/callcenter/extention.html?hostid="+extention.getHostid()+(ismy?"&ismy=true":"")));
    }
	
	@RequestMapping(value = "/extention/ivr")
    @Menu(type = "callcenter" , subtype = "extention" , access = false )
    public ModelAndView ivr(ModelMap map , HttpServletRequest request , @Valid String id , @Valid String hostid,@Valid boolean ismy) {
		Extention ext = null;
		//多租户下超级管理员可以编辑其他租户
		if(super.isEnabletneantAndSuperUser(request)){
			ext = extentionRes.findById(id) ;
		}else{
			ext = extentionRes.findByIdAndOrgi(id, super.getOrgi(request)) ;
		}
		map.addAttribute("extention" ,ext);
		if(super.isEnabletneant()){
			map.addAttribute("pbxHost" , pbxHostRes.findById(hostid));
		}else{
			map.addAttribute("pbxHost" , pbxHostRes.findByIdAndOrgi(hostid, super.getOrgi(request)));
		}
		map.put("mediaList" , mediaRes.findByHostidAndOrgi(hostid, super.getOrgi(request)));
		map.addAttribute("sipTrunkListList" , sipTrunkRes.findByHostidAndOrgi(hostid, super.getOrgi(request)));
		
		map.put("serviceAiList",serviceAiRes.findByOrgi(super.getOrgi(request)) ) ;
		map.put("queList",queSurveyProcessRes.findByOrgi(super.getOrgi(request)) ) ;
		map.put("salesPatterList",salesPatterRes.findByOrgi(super.getOrgi(request)) ) ;
		if (ismy) {
			map.addAttribute("ismy",true);
		}
		map.put("p",request.getParameter("p")) ;
    	return request(super.createRequestPageTempletResponse("/admin/callcenter/extention/ivr"));
    }
	
	@RequestMapping(value = "/extention/ivr/update")
    @Menu(type = "callcenter" , subtype = "extention" , access = false )
    public ModelAndView ivrupdate(ModelMap map , HttpServletRequest request , @Valid Extention extention,@Valid boolean ismy) {
		if(!StringUtils.isBlank(extention.getId())){
			Extention ext = null;
			//多租户下超级管理员可以编辑其他租户
			if(super.isEnabletneantAndSuperUser(request)){
				ext = extentionRes.findById(extention.getId()) ;
			}else{
				ext = extentionRes.findByIdAndOrgi(extention.getId(), super.getOrgi(request)) ;
			}
			if(ext!=null){
				
				ext.setEnableai(extention.getEnableai());
				ext.setAiid(extention.getAiid());
				ext.setSceneid(extention.getSceneid());           
				ext.setWelcomemsg(extention.getWelcomemsg()) ;        
				ext.setWaitmsg(extention.getWaitmsg())       ;     
				ext.setTipmessage(extention.getTipmessage());
				
				ext.setErrormessage(extention.getErrormessage());
				
				ext.setAfterprocess(extention.isAfterprocess());
				
				ext.setAitype(extention.getAitype());
				ext.setBustype(extention.getBustype());
				ext.setProid(extention.getProid());
				ext.setQueid(extention.getQueid());
				
				ext.setWaittime(extention.getWaittime());
				ext.setWaittiptimes(extention.getWaittiptimes());
				ext.setLanguage(extention.getLanguage());

				ext.setEoseng(extention.getEoseng());
				ext.setSoseng(extention.getSoseng());
				ext.setEostime(extention.getEostime());
				
				ext.setDenoise(extention.getDenoise());
				
				extentionRes.save(ext) ;
				
				if(RobotTools.extention(ext.getExtention())) {
					RobotTools.putExtention(ext.getExtention(), ext);
				}
			}
		}
		return request(super.createRequestPageTempletResponse("redirect:/admin/callcenter/extention.html?hostid="+extention.getHostid()+(ismy?"&ismy=true":"")+"&p="+request.getParameter("p")));
    }
	
	@RequestMapping(value = "/extention/delete")
    @Menu(type = "callcenter" , subtype = "extention" , access = false )
    public ModelAndView extentiondelete(ModelMap map , HttpServletRequest request , @Valid String id , @Valid String hostid) {
		if(!StringUtils.isBlank(id)){
			Extention extention = null;

			//多租户下超级管理员可以编辑其他租户
			if(super.isEnabletneantAndSuperUser(request)){
				extention = extentionRes.findById(id) ;
			}else{
				extention = extentionRes.findByIdAndOrgi(id, super.getOrgi(request)) ;
			}

			if(extention!=null && !StringUtils.isBlank(extention.getUserid())) {
				User user = null;
				//多租户下超级管理员可以编辑其他租户
				if(super.isEnabletneantAndSuperUser(request)){
					user = userRes.findById(extention.getUserid()) ;
				}else{
					user = userRes.findByIdAndOrgi(extention.getUserid(), super.getOrgi(request)) ;
				}
				if(user!=null) {
					user.setBindext(false);
					user.setExtid(null);
					user.setExtno(null);
					user.setHostid(null);
					userRes.save(user) ;
				}
			}
			extentionRes.delete(id);
			
			if(extention!=null && RobotTools.extention(extention.getExtention())) {
				RobotTools.putExtention(extention.getExtention(), null);
			}
		}
		return request(super.createRequestPageTempletResponse("redirect:/admin/callcenter/extention.html?hostid="+hostid));
    }
	
	@RequestMapping(value = "/extention/batdelete")
    @Menu(type = "callcenter" , subtype = "extention" , access = false )
    public ModelAndView batdelete(ModelMap map , HttpServletRequest request , @Valid String[] ids, @Valid String hostid) {
		if(ids!=null && ids.length > 0){
			List<Extention> extentions = new ArrayList<Extention>();
			for(String id : ids) {
				Extention extention = null;
	
				//多租户下超级管理员可以编辑其他租户
				if(super.isEnabletneantAndSuperUser(request)){
					extention = extentionRes.findById(id) ;
				}else{
					extention = extentionRes.findByIdAndOrgi(id, super.getOrgi(request)) ;
				}
	
				if(extention!=null && !StringUtils.isBlank(extention.getUserid())) {
					User user = null;
					//多租户下超级管理员可以编辑其他租户
					if(super.isEnabletneantAndSuperUser(request)){
						user = userRes.findById(extention.getUserid()) ;
					}else{
						user = userRes.findByIdAndOrgi(extention.getUserid(), super.getOrgi(request)) ;
					}
					if(user!=null) {
						user.setBindext(false);
						user.setExtid(null);
						user.setExtno(null);
						user.setHostid(null);
						userRes.save(user) ;
					}
				}
				if(extention!=null) {
					extentions.add(extention);
				}
			}
			if(extentions.size() > 0) {
				extentionRes.delete(extentions);
			}
		}
		return request(super.createRequestPageTempletResponse("redirect:/admin/callcenter/extention.html?hostid="+hostid));
    }
	
	@RequestMapping(value = "/extention/assign")
	@Menu(type = "callcenter" , subtype = "extention" , access = false )
	public ModelAndView extentionAssign(ModelMap map , HttpServletRequest request , @Valid final String hostid) {
		map.addAttribute("hostid" , hostid);
		//多租户下超级管理员可以编辑其他租户
		if(super.isEnabletneantAndSuperUser(request)){
			List<Extention> extentionList = extentionRes.findAll(new Specification<Extention>() {
				@Override
				public Predicate toPredicate(Root<Extention> root,
											 CriteriaQuery<?> query, CriteriaBuilder cb) {
					List<Predicate> list = new ArrayList<Predicate>();
					list.add(cb.equal(root.get("hostid").as(String.class), hostid));
					//查出未分配的
					list.add(cb.equal(root.get("assigned").as(Boolean.class),false));
					Predicate[] p = new Predicate[list.size()];

					query.where(cb.and(list.toArray(p)));
					//添加排序的功能
					query.orderBy(cb.asc(root.get("extention").as(String.class)));

					return query.getRestriction();

				}
			});
			//启用多租户和超级管理员 显示全部
			map.addAttribute("extentionList" , extentionList);

			map.addAttribute("tenantList",tenantRepository.findByDatastatus(false));

		}

		return request(super.createRequestPageTempletResponse("/admin/callcenter/extention/assign"));
	}

	/**
	 * 将分机分配给租户
	 * @param map
	 * @param request
	 * @param ids
	 * @param hostid
	 * @param orgi
	 * @return
	 */
	@RequestMapping(value = "/extention/assigned")
	@Menu(type = "callcenter" , subtype = "extention" , access = false )
	public ModelAndView extentionassign(ModelMap map , HttpServletRequest request , @Valid String ids , @Valid String hostid , @Valid String orgi) {
		//多租户下超级管理员可以编辑其他租户
		if(super.isEnabletneantAndSuperUser(request)){

			if(ids != null && StringUtils.isNotBlank(ids)){

				String[] extentions = ids.split("[,\\|，]");;

				if(extentions.length > 0 ){

					for(String nb : extentions){
						if(StringUtils.isNotBlank(nb)){
							Extention extention = extentionRes.findById(nb) ;
							if(extention!=null) {
								extention.setOrgi(orgi);
								extention.setAssigned(true);
								extentionRes.save(extention);
							}
						}
					}
				}
			}
		}

		return request(super.createRequestPageTempletResponse("redirect:/admin/callcenter/extention.html?hostid="+hostid));
	}


	/**
	 * 取消 分配给租户
	 * @param map
	 * @param request
	 * @param id
	 * @param hostid
	 * @return
	 */
	@RequestMapping(value = "/extention/cancelassigned")
	@Menu(type = "callcenter" , subtype = "extention" , access = false )
	public ModelAndView extentioncancelAssign(ModelMap map , HttpServletRequest request , @Valid String id , @Valid String hostid ) {
		//多租户下超级管理员可以编辑其他租户
		if(super.isEnabletneantAndSuperUser(request)){

			if(id != null && StringUtils.isNotBlank(id)){
				Extention extention = extentionRes.findById(id) ;
				if(extention!=null) {
					extention.setOrgi(UKDataContext.SYSTEM_ORGI);
					extention.setAssigned(false);
					extentionRes.save(extention);
				}
			}
		}

		return request(super.createRequestPageTempletResponse("redirect:/admin/callcenter/extention.html?hostid="+hostid+"&p="+request.getParameter("p")));
	}
}
